package com.corn.juc.lock;

import java.util.concurrent.TimeUnit;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/1/5 15:06
 */

/**
 * 控制输出 程序卡死
 * Thread1	 enter get LCOK1
 * Thread2	 enter get LOCK2
 */
class TestThread implements Runnable {

    private final String lock1;

    private final String lock2;

    public TestThread(String lock1, String lock2) {
        this.lock1 = lock1;
        this.lock2 = lock2;
    }

    @Override
    public void run() {
        synchronized (lock1) {
            System.out.println(Thread.currentThread().getName() + "\t enter get " + lock1);
            try {
                // 模拟耗时操作
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock2) {
                System.out.println(Thread.currentThread().getName() + "\t enter get lock2" + lock2);
            }
        }
    }
}

public class DeadLockDemo {

    private static final String LOCK1 = "LCOK1";

    private static final String LOCK2 = "LOCK2";

    public static void main(String[] args) {
        new Thread(new TestThread(LOCK1, LOCK2), "Thread1").start();
        new Thread(new TestThread(LOCK2, LOCK1), "Thread2").start();
    }
}
